<template>
  <div class="projects-container">
    <div class="projects-header">
      <h1>项目管理</h1>
      <el-button type="primary" @click="showCreateProjectDialog">创建新项目</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="projects"
      style="width: 100%"
      @row-click="handleRowClick">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="项目名称" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="start_date" label="开始日期" width="120" />
      <el-table-column prop="planned_end_date" label="计划结束日期" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="progress" label="进度" width="180">
        <template #default="scope">
          <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click.stop="editProject(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click.stop="deleteProject(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建项目对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建新项目"
      width="50%">
      <el-form :model="projectForm" :rules="rules" ref="projectFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目编码" prop="code">
          <el-input v-model="projectForm.code" placeholder="请输入项目编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="projectForm.description" type="textarea" placeholder="请输入项目描述" />
        </el-form-item>
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker v-model="projectForm.start_date" type="date" placeholder="选择开始日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="计划结束日期" prop="planned_end_date">
          <el-date-picker v-model="projectForm.planned_end_date" type="date" placeholder="选择计划结束日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="projectForm.status" placeholder="请选择项目状态" style="width: 100%">
            <el-option label="规划中" value="planning" />
            <el-option label="启动中" value="initiating" />
            <el-option label="执行中" value="executing" />
            <el-option label="监控中" value="monitoring" />
            <el-option label="结束中" value="closing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="on_hold" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="预算" prop="budget">
          <el-input-number v-model="projectForm.budget" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="projectForm.priority" :min="0" :max="10" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProjectForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑项目对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑项目"
      width="50%">
      <el-form :model="projectForm" :rules="rules" ref="projectFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目编码" prop="code">
          <el-input v-model="projectForm.code" placeholder="请输入项目编码" disabled />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="projectForm.description" type="textarea" placeholder="请输入项目描述" />
        </el-form-item>
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker v-model="projectForm.start_date" type="date" placeholder="选择开始日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="计划结束日期" prop="planned_end_date">
          <el-date-picker v-model="projectForm.planned_end_date" type="date" placeholder="选择计划结束日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="projectForm.status" placeholder="请选择项目状态" style="width: 100%">
            <el-option label="规划中" value="planning" />
            <el-option label="启动中" value="initiating" />
            <el-option label="执行中" value="executing" />
            <el-option label="监控中" value="monitoring" />
            <el-option label="结束中" value="closing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="on_hold" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="预算" prop="budget">
          <el-input-number v-model="projectForm.budget" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="projectForm.priority" :min="0" :max="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="进度" prop="progress">
          <el-slider v-model="projectForm.progress" :step="5" show-stops />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateProject">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ProjectsView',
  setup() {
    const store = useStore()
    const router = useRouter()
    const projectFormRef = ref(null)
    
    const loading = ref(true)
    const createDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    
    const projectForm = reactive({
      id: '',
      name: '',
      code: '',
      description: '',
      start_date: '',
      planned_end_date: '',
      status: 'planning',
      budget: 0,
      priority: 0
    })
    
    const rules = {
      name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入项目编码', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      description: [
        { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
      ],
      start_date: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
      ],
      planned_end_date: [
        { required: true, message: '请选择计划结束日期', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择项目状态', trigger: 'change' }
      ]
    }
    
    // 模拟项目数据
    const projects = ref([
      {
        id: 1,
        name: '企业官网重构项目',
        description: '对公司官网进行全面重构，提升用户体验和品牌形象',
        start_date: '2023-01-15',
        end_date: '2023-04-30',
        status: '进行中',
        progress: 65
      },
      {
        id: 2,
        name: '移动应用开发',
        description: '开发公司产品的移动应用版本，支持iOS和Android平台',
        start_date: '2023-02-01',
        end_date: '2023-06-30',
        status: '进行中',
        progress: 40
      },
      {
        id: 3,
        name: '数据分析平台',
        description: '构建内部使用的数据分析平台，支持数据可视化和报表生成',
        start_date: '2022-11-01',
        end_date: '2023-03-31',
        status: '已完成',
        progress: 100
      }
    ])
    
    // 获取项目列表
    const fetchProjects = async () => {
      loading.value = true
      try {
        const response = await store.dispatch('fetchProjects')
        projects.value = response
      } catch (error) {
        ElMessage.error('获取项目列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 显示创建项目对话框
    const showCreateProjectDialog = () => {
      resetProjectForm()
      createDialogVisible.value = true
    }
    
    // 重置表单
    const resetProjectForm = () => {
      projectForm.id = ''
      projectForm.name = ''
      projectForm.code = ''
      projectForm.description = ''
      projectForm.start_date = ''
      projectForm.planned_end_date = ''
      projectForm.status = 'planning'
      projectForm.budget = 0
      projectForm.priority = 0
      
      if (projectFormRef.value) {
        projectFormRef.value.resetFields()
      }
    }
    
    // 提交项目表单
    const submitProjectForm = () => {
      projectFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            await store.dispatch('createProject', projectForm)
            ElMessage.success('创建项目成功')
            createDialogVisible.value = false
            fetchProjects() // 重新获取项目列表
          } catch (error) {
            ElMessage.error('创建项目失败')
          }
        }
      })
    }
    
    // 编辑项目
    const editProject = (project) => {
      Object.assign(projectForm, project)
      editDialogVisible.value = true
    }
    
    // 更新项目
    const updateProject = () => {
      projectFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            await store.dispatch('updateProject', { id: projectForm.id, data: projectForm })
            ElMessage.success('更新项目成功')
            editDialogVisible.value = false
            fetchProjects() // 重新获取项目列表
          } catch (error) {
            ElMessage.error('更新项目失败')
          }
        }
      })
    }
    
    // 删除项目
    const deleteProject = (project) => {
      ElMessageBox.confirm(
        '确定要删除该项目吗？删除后无法恢复。',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          await store.dispatch('deleteProject', project.id)
          ElMessage.success('删除项目成功')
          fetchProjects() // 重新获取项目列表
        } catch (error) {
          ElMessage.error('删除项目失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 行点击事件
    const handleRowClick = (row) => {
      router.push(`/projects/${row.id}`)
    }
    
    // 获取状态对应的类型
    const getStatusType = (status) => {
      const statusMap = {
        'planning': 'info',
        'initiating': 'warning',
        'executing': 'primary',
        'monitoring': 'success',
        'closing': 'warning',
        'completed': 'success',
        'on_hold': 'warning',
        'cancelled': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态对应的文本
    const getStatusText = (status) => {
      const statusMap = {
        'planning': '规划中',
        'initiating': '启动中',
        'executing': '执行中',
        'monitoring': '监控中',
        'closing': '结束中',
        'completed': '已完成',
        'on_hold': '已暂停',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 获取进度对应的状态
    const getProgressStatus = (progress) => {
      if (progress >= 100) return 'success'
      if (progress >= 80) return 'success'
      if (progress >= 50) return ''
      if (progress >= 20) return 'warning'
      return 'exception'
    }
    
    onMounted(() => {
      fetchProjects()
    })
    
    return {
      loading,
      projects,
      projectForm,
      projectFormRef,
      rules,
      createDialogVisible,
      editDialogVisible,
      showCreateProjectDialog,
      submitProjectForm,
      editProject,
      updateProject,
      deleteProject,
      handleRowClick,
      getStatusType,
      getStatusText,
      getProgressStatus
    }
  }
}
</script>

<style scoped>
.projects-container {
  padding: 20px;
}

.projects-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>